package com.authentication.filter;

import com.authentication.code.AuthenticationCodeRepository;
import com.authentication.code.ClientAndUserAuthenticationPair;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeRequestAuthenticationToken;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

public class CodeStateAuthenticationFilter extends OncePerRequestFilter {

    public final static ThreadLocal<String[]> USER_GRANTED_AUTHORITIES = new ThreadLocal<>();

    private final AuthenticationCodeRepository authenticationCodeRepository;

    public CodeStateAuthenticationFilter(AuthenticationCodeRepository authenticationCodeRepository) {
        this.authenticationCodeRepository = authenticationCodeRepository;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String code = request.getParameter("code");

        if(!StringUtils.hasLength(code)){
//          accessToken 过期 ,使用 refresh token 来刷新 accessToken

            filterChain.doFilter(request,response);
            return;
        }
//        第一次使用 authorization code 换取 accessToken
        ClientAndUserAuthenticationPair clientAndUserAuthenticationPair = authenticationCodeRepository.get(code);

        OAuth2AuthorizationCodeRequestAuthenticationToken clientAuthenticationToken = clientAndUserAuthenticationPair.getClientAuthenticationToken();

//        SecurityContextHolder.getContext().setAuthentication(clientAuthenticationToken);

        USER_GRANTED_AUTHORITIES.set(clientAndUserAuthenticationPair.getGrantedScopes());

        try {
            filterChain.doFilter(request, response);
        } finally {
            USER_GRANTED_AUTHORITIES.remove();
        }
    }
}
